/**
 * @Author: Kindear
 * @Date: 2021-09-05
 * @Desc: 用于查询课表的云函数构建
 */

/**
 * @feature:云函数存在参数不一致的情况 _zc zc week 参数幂等 但是表现形式不一致
 * @Date:2021-09-06
 */

/**
 * @BUG:对于提交的数据要进行表单校验
 * @Date:2021-09-07
 */
if (!Promise.allSettled) {
    const rejectHandler = reason => ({
        status: "rejected",
        reason
    })
    const resolveHandler = value => ({
        status: "fulfilled",
        value
    })
    Promise.allSettled = promises =>
        Promise.all(
            promises.map((promise) =>
                Promise.resolve(promise)
                .then(resolveHandler, rejectHandler)
            )
            // 每个 promise 需要用 Promise.resolve 包裹下
            // 以防传递非 promise
        );
}
async function execPromise(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.all(tasks).then(res => {
            resolve(res)
            reject(res)
        })
    })
}
async function execPromiseSettled(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.allSettled(tasks).then(res => {
            resolve(res)
            reject(res)
        })
    })
}
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const TIME_TABLE = 'cloud-edu-timetable';
const TIME_TABLE_EX = 'cloud-edu-timetable-extend';
const USER = 'edu-cloud-users'
const timeutil = require('./timeutil');
const formValid = require("./formValidation")
const dayjs = require('dayjs');
const SUMMER_START_DAY = '09-01';
const WINTER_START_DAY = '02-27';
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    const openid = event.openid || wxContext.OPENID;
    let action = event.action;
    /**获取基础的用户信息 */
    let userBase = {}
    let queryRes = await db.collection(USER).where({
        openid
    }).get();
    if (queryRes.data.length == 0) {
        return {
            errCode: -1,
            errMsg: '未绑定学号信息'
        }
    } else {
        userBase = queryRes.data[0];
    }
    let nowDate = dayjs();
    /**获取当前年份 */
    let year = dayjs().year();
    console.log(year)
    /**获取当前月份 */
    let month = dayjs().month() + 1;
    console.log(month);
    /**学期 */
    let semester = 1;
    /**构建开学日期 */
    let startDay = ''
    /**获取学年信息 */
    let studyYear = 0
    if (month >= 9 || month < 2) {
        startDay = year + '-' + SUMMER_START_DAY;
        studyYear = parseInt(year)
        semester = 1
    } else if (month >= 2 && month <= 8) {
        startDay = year + '-' + WINTER_START_DAY
        studyYear = parseInt(year) - 1
        semester = 2
    }
    let startDate = dayjs(startDay);
    /**获取相差天数，计算当前周次 */
    let hours = nowDate.diff(startDate, 'hours');
    console.log(hours)
    const days = Math.floor(hours / 24);
    //zc 幂等于 week
    let zc = parseInt(days / 7) + 1;
    switch (action) {
        case 'initTable': {
            /**检索自定课表信息 */
            let customQueryRes = await db.collection(TIME_TABLE_EX).where({
                xh: userBase.bindId,
                studyYear,
                semester,
                weeks: zc
            }).get();
            console.log(customQueryRes)
            /**优先检索数据 */
            let timeQueryRes = await db.collection(TIME_TABLE).where({
                xh: userBase.bindId,
                studyYear,
                semester,
                week: zc
            }).get();
            if (timeQueryRes.data.length != 0) {
                let baseRes = timeQueryRes.data[0];
                return {
                    timetableData: baseRes.timetableData.concat(customQueryRes.data),
                    currentWeek: zc,
                    semester
                }
            } else {
                /**请求获取当前用户课表 */
                let timetableRes = await cloud.callFunction({
                    name: 'edu-cloud-api',
                    data: {
                        action: 'getKbcxAzc',
                        openid,
                        resHandle: true,
                        week: zc
                    }
                })
                /**数据表新建，存储对应数据 */
                if (timetableRes.result.errCode != -1) {
                    /**没有报错 */
                    db.collection(TIME_TABLE).add({
                        data: {
                            studyYear,
                            semester,
                            week: zc,
                            xh: userBase.bindId,
                            timetableData: timetableRes.result,
                            _createTime: timeutil.TimeCode(),
                            _updateTime: timeutil.TimeCode()
                        }
                    })
                }
                return {
                    timetableData: timetableRes.result,
                    currentWeek: zc,
                    semester
                };
            }
            break
        }
        case 'queryTable': {
            //周次
            let _zc = event.zc || zc;
            /**检索自定课表信息 */
            let customQueryRes = await db.collection(TIME_TABLE_EX).where({
                xh: userBase.bindId,
                studyYear,
                semester,
                weeks: _zc
            }).get();
            console.log(customQueryRes)
            /**优先检索数据 */
            let timeQueryRes = await db.collection(TIME_TABLE).where({
                xh: userBase.bindId,
                studyYear,
                semester,
                week: _zc
            }).get();
            if (timeQueryRes.data.length != 0) {
                let baseRes = timeQueryRes.data[0];
                return {
                    timetableData: baseRes.timetableData.concat(customQueryRes.data),
                    currentWeek: _zc,
                    semester: semester
                }
            } else {
                /**请求获取当前用户课表 */
                let timetableRes = await cloud.callFunction({
                    name: 'edu-cloud-api',
                    data: {
                        action: 'getKbcxAzc',
                        openid,
                        resHandle: true,
                        week: _zc
                    }
                })
                /**数据表新建，存储对应数据 */
                if (timetableRes.result.errCode != -1) {
                    /**没有报错 */
                    db.collection(TIME_TABLE).add({
                        data: {
                            studyYear,
                            semester,
                            week: _zc,
                            xh: userBase.bindId,
                            timetableData: timetableRes.result,
                            _createTime: timeutil.TimeCode(),
                            _updateTime: timeutil.TimeCode()
                        }
                    })
                }
                return {
                    timetableData: timetableRes.result,
                    currentWeek: _zc,
                    semester
                };
            }
            break
        }
        case 'deleteCustom':{
            let docId = event.docId;
            return await db.collection(TIME_TABLE_EX).doc(docId).remove();
            break
        }
        // case 'addTableAll': {
        //     /**批量新增课程 */
        //     let weeks = event.weeks;
        //     let promiseTasks = [];
        //     weeks.forEach(function (ele, index) {
        //         let obj = event;
        //         obj.openid = openid;
        //         obj.week = ele;
        //         obj.action = 'addTable';
        //         promiseTasks.push(cloud.callFunction({
        //             name: 'edu-timetable-api',
        //             data: obj
        //         }))
        //     })
        //     let resList = await execPromiseSettled(promiseTasks);
        //     return resList;
        //     break
        // }
        case 'addTable': {
            // console.log(openid)
            /**新增课表 */
            console.log(event)
            let weeks = event.weeks;
            /**查询当前课表 */
            // let courseData = await cloud.callFunction({
            //     name: 'edu-timetable-api',
            //     data: {
            //         openid,
            //         action: 'queryTable',
            //         zc: week
            //     }
            // })
            // /**设置可插入状态为true */
            // let insertFlag = true;
            // let timetableData = courseData.result.timetableData;
            // /**遍历已存在课表 -- 判断是否满足插入条件 */
            // timetableData.forEach(function (ele, index) {
            //     if (ele.days == event.days) {
            //         //同一天，查询
            //         if (event.nums <= ele.nums && event.enum >= ele.enum) {
            //             insertFlag = false
            //             console.log(ele.days + ele.kcmc + '冲突')
            //         } else if (event.nums <= ele.enum && event.enum >= ele.enum) {
            //             console.log(ele.days + ele.kcmc + '冲突')
            //             insertFlag = false
            //         }
            //     }
            // })
            /**进行表单校验 */
            let obj = {
                xh: userBase.bindId,
                studyYear,
                semester,
                weeks,
                days: event.days,
                subject_id: parseInt(Math.round(Math.random() * 10000)),
                sname: event.sname,
                classroom: event.classroom,
                jsmc: event.classroom,
                jsxm: event.jsxm,
                kcsj: event.days + timeutil.formatNumber(event.nums) + timeutil.formatNumber(event.enum),
                nums: event.nums,
                enum: event.enum,
                kssj: event.kssj,
                _createTime: timeutil.TimeCode(),
                _updateTime: timeutil.TimeCode()
            }
            let rules = [{
                    name: "xh",
                    rule: ["required"],
                    msg: ["该用户未绑定学号"]
                },
                {
                    name: "weeks",
                    rule: ["required"],
                    msg: ["请选择周次"]
                },
                {
                    name: "days",
                    rule: ["required"],
                    msg: ["请选择星期几"]
                },
                {
                    name: "sname",
                    rule: ["required"],
                    msg: ["请填写课程名称"]
                },
                {
                    name: "classroom",
                    rule: ["required"],
                    msg: ["请填写教室名称"]
                },
                {
                    name: "jsxm",
                    rule: ["required"],
                    msg: ["请填写教师姓名"]
                }
            ]
            let checkRes = formValid.validation(obj, rules);
            if (!checkRes) {
                /**如果不存在冲突情况 */
                return await db.collection(TIME_TABLE_EX).add({
                    data: obj
                })
            } else {
                return {
                    errCode: -1,
                    errMsg: checkRes
                }
            }

            // if (insertFlag) {
            //     /**写入自定义课表 */

            // } else {
            //     return {
            //         errCode: -1,
            //         errMsg: '存在冲突课程'
            //     }
            // }
            break
        }
        /**查询自定义课表 */
        case 'queryCustomTable':{
            let customCourse = await db.collection(TIME_TABLE_EX).where({
                xh:userBase.bindId
            }).get();
            return customCourse.data;
            break
        }
    }
}